import 'package:core/mvi/bloc_mvi.dart';
import 'package:domain/model/projects_domain_model.dart';
import 'package:domain/usecases/projects_use_case.dart';
import 'package:feature_projects/projects/effect.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import 'event.dart';
import 'state.dart';

class ProjectsViewModel
    extends BlocMviViewModel<ProjectsEvent, ProjectsState, ProjectsEffect> {
  final ProjectsUseCase _useCase;
  var _currentPageIndex = 1;
  static const int defaultChapterId = 294;

  ProjectsViewModel({required ProjectsUseCase useCase})
    : _useCase = useCase,
      super(ProjectsState.init());

  @override
  void subscribeEvents() {
    on<InitEvent>(_processInitEvent);
    on<RefreshEvent>(_processRefreshEvent);
    on<LoadMoreEvent>(_processLoadMoreEvent);
  }

  void _processInitEvent(InitEvent event, Emitter<ProjectsState> emit) async {
    final (totalCount, list) = await _fetchProjects(
      _currentPageIndex,
      defaultChapterId,
    );

    emit(state.copyWith(isLoading: false, list: list));
  }

  void _processRefreshEvent(
    RefreshEvent event,
    Emitter<ProjectsState> emit,
  ) async {
    _currentPageIndex = 1;
    final (totalCount, list) = await _fetchProjects(
      _currentPageIndex,
      defaultChapterId,
    );
    emit(state.copyWith(list: list));
    sendEffect(RefreshingFinished());
  }

  void _processLoadMoreEvent(
    LoadMoreEvent event,
    Emitter<ProjectsState> emit,
  ) async {
    ++_currentPageIndex;
    final (totalCount, list) = await _fetchProjects(
      _currentPageIndex,
      defaultChapterId,
    );
    final newList = List<Project>.from(state.list)..addAll(list);
    emit(state.copyWith(list: newList));
    sendEffect(LoadingMoreFinished());
  }

  Future<(int, List<Project>)> _fetchProjects(int page, int chapterId) async {
    final result = await _useCase.fetchProjects(
      page: page,
      chapterId: chapterId,
    );
    return (result.totalCount, result.projects);
  }
}
